package com.sinogrand.elevator.ui.screens

import android.webkit.WebView
import android.webkit.WebViewClient
import android.webkit.WebChromeClient
import android.webkit.JavascriptInterface
import android.webkit.ValueCallback
import android.net.Uri
import android.os.Environment
import android.content.pm.PackageManager
import android.os.Build
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.viewinterop.AndroidView
import androidx.compose.ui.zIndex
import androidx.core.content.ContextCompat
import androidx.core.content.FileProvider
import com.sinogrand.elevator.utils.LogTags
import com.sinogrand.elevator.utils.LocationManager
import com.sinogrand.elevator.utils.EnvironmentManager
import android.util.Log
import com.google.gson.JsonParser
import java.io.File
import java.text.SimpleDateFormat
import java.util.*
import androidx.compose.material.icons.filled.Error
import kotlinx.coroutines.delay
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import android.app.ActivityManager
import android.content.Context
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.DisposableEffect

/**
 * JavaScript接口类，用于接收网页发送的文件信息和定位请求
 */
class WebAppInterface(
    private val context: android.content.Context,
    private val onExit: () -> Unit,
    private val locationManager: LocationManager,
    private val webView: android.webkit.WebView,
    private val onNavigateToFileViewer: (String, String) -> Unit
) {
    
    @JavascriptInterface
    fun openFile(fileDataJson: String) {
        try {
            Log.d(LogTags.APPROVAL_SCREEN, "📁 接收到文件信息: $fileDataJson")
            
            // 解析JSON数据
            val jsonObject = JsonParser.parseString(fileDataJson).asJsonObject
            
            val url = jsonObject.get("url")?.asString ?: ""
            val name = jsonObject.get("name")?.asString ?: "未知文件"
            val type = jsonObject.get("type")?.asString ?: ""
            val size = jsonObject.get("size")?.asLong ?: 0L
            
            Log.i(LogTags.APPROVAL_SCREEN, "📁 文件信息解析:")
            Log.i(LogTags.APPROVAL_SCREEN, "   📄 文件名: $name")
            Log.i(LogTags.APPROVAL_SCREEN, "   🔗 文件地址: $url")
            Log.i(LogTags.APPROVAL_SCREEN, "   📋 文件类型: $type")
            Log.i(LogTags.APPROVAL_SCREEN, "   📏 文件大小: ${size} bytes")
            
            // 记录文件信息，可以在这里添加其他处理逻辑
            Log.i(LogTags.APPROVAL_SCREEN, "📁 文件信息已记录，URL: $url")
            
            // 使用应用内WebView打开文件
            if (url.isNotEmpty()) {
                Log.i(LogTags.APPROVAL_SCREEN, "🚀 使用应用内WebView打开文件: $url")
                // 在主线程中执行导航操作
                android.os.Handler(android.os.Looper.getMainLooper()).post {
                    try {
                        onNavigateToFileViewer(url, name)
                        Log.i(LogTags.APPROVAL_SCREEN, "✅ 成功导航到文件查看器")
                    } catch (e: Exception) {
                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 导航到文件查看器失败: ${e.message}", e)
                    }
                }
            } else {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 文件URL为空，无法打开")
            }
            
            // 以下是原来的外部浏览器打开代码（已注释）
            /*
            // 使用外部浏览器打开文件
            if (url.isNotEmpty()) {
                Log.i(LogTags.APPROVAL_SCREEN, "🚀 使用外部浏览器打开文件: $url")
                // 在主线程中执行浏览器打开操作
                android.os.Handler(android.os.Looper.getMainLooper()).post {
                    try {
                        val intent = android.content.Intent(android.content.Intent.ACTION_VIEW, android.net.Uri.parse(url))
                        intent.addFlags(android.content.Intent.FLAG_ACTIVITY_NEW_TASK)
                        context.startActivity(intent)
                        Log.i(LogTags.APPROVAL_SCREEN, "✅ 成功打开外部浏览器")
                    } catch (e: Exception) {
                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 打开外部浏览器失败: ${e.message}", e)
                    }
                }
            } else {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 文件URL为空，无法打开")
            }
            */
            
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 解析文件信息失败: ${e.message}", e)
        }
    }
    
    @JavascriptInterface
    fun notifyAppToGoBack() {
        try {
            Log.i(LogTags.APPROVAL_SCREEN, "🔙 网页请求返回上一页")
            
            // 在主线程中执行返回上一页操作
            android.os.Handler(android.os.Looper.getMainLooper()).post {
                try {
                    Log.i(LogTags.APPROVAL_SCREEN, "✅ 执行返回上一页操作")
                    onExit()
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 执行返回上一页操作失败: ${e.message}", e)
                }
            }
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 处理返回上一页请求失败: ${e.message}", e)
        }
    }
    
    @JavascriptInterface
    fun goBack() {
        try {
            Log.i(LogTags.APPROVAL_SCREEN, "🔙 网页调用goBack方法")
            notifyAppToGoBack()
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ goBack方法调用失败: ${e.message}", e)
        }
    }
    
    @JavascriptInterface
    fun exitPage() {
        try {
            Log.i(LogTags.APPROVAL_SCREEN, "🔙 网页调用exitPage方法")
            notifyAppToGoBack()
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ exitPage方法调用失败: ${e.message}", e)
        }
    }
    
    @JavascriptInterface
    fun getCurrentLocation() {
        try {
            Log.i(LogTags.APPROVAL_SCREEN, "📍 网页请求获取当前位置")
            
            // 在主线程中执行定位获取
            android.os.Handler(android.os.Looper.getMainLooper()).post {
                try {
                    // 重新开始获取位置
                    locationManager.startLocationUpdates()
                    
                    // 获取当前位置信息
                    val locationInfo = locationManager.getLocationInfoString()
                    Log.i(LogTags.APPROVAL_SCREEN, "📍 当前定位信息: $locationInfo")
                    
                    // 通过JavaScript回调将位置信息传递给网页
                    webView.evaluateJavascript("""
                        if (window.setLocationInfo) {
                            window.setLocationInfo('$locationInfo');
                        }
                    """.trimIndent()) { result ->
                        Log.i(LogTags.APPROVAL_SCREEN, "📍 位置信息已传递给网页: $result")
                    }
                    
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 获取位置信息失败: ${e.message}", e)
                    
                    // 如果获取失败，传递空字符串给网页
                    webView.evaluateJavascript("""
                        if (window.setLocationInfo) {
                            window.setLocationInfo('');
                        }
                    """.trimIndent()) { result ->
                        Log.w(LogTags.APPROVAL_SCREEN, "📍 位置信息获取失败，已传递空值: $result")
                    }
                }
            }
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 处理定位请求失败: ${e.message}", e)
        }
    }
    
    @JavascriptInterface
    fun getAvailableMethods(): String {
        try {
            Log.i(LogTags.APPROVAL_SCREEN, "📋 网页请求获取可用方法列表")
            val methods = listOf(
                "openFile",
                "notifyAppToGoBack",
                "goBack",
                "exitPage",
                "getCurrentLocation",
                "getAvailableMethods"
            )
            val result = methods.joinToString(",")
            Log.i(LogTags.APPROVAL_SCREEN, "📋 返回可用方法: $result")
            return result
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 获取可用方法失败: ${e.message}", e)
            return "error"
        }
    }
}

/**
 * 创建图片文件 - 优化版本
 */
private fun createImageFile(context: android.content.Context): File {
    try {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "Camera")
        
        Log.d(LogTags.APPROVAL_SCREEN, "📁 创建图片文件目录: ${storageDir.absolutePath}")
        
        // 确保目录存在
        if (!storageDir.exists()) {
            val created = storageDir.mkdirs()
            Log.d(LogTags.APPROVAL_SCREEN, "📁 创建目录结果: $created")
        }
        
        val fileName = "IMG_${timeStamp}"
        val fileExtension = ".jpg"
        
        Log.d(LogTags.APPROVAL_SCREEN, "📁 创建图片文件: $fileName$fileExtension")
        
        // 使用更简单的文件名，减少系统负担
        val file = File(storageDir, "$fileName$fileExtension")
        
        // 创建空文件，不写入任何内容
        if (!file.exists()) {
            file.createNewFile()
        }
        
        Log.i(LogTags.APPROVAL_SCREEN, "✅ 图片文件创建成功: ${file.absolutePath}")
        Log.i(LogTags.APPROVAL_SCREEN, "✅ 图片文件大小: ${file.length()} bytes")
        
        // 强制垃圾回收，释放内存
        System.gc()
        
        return file
    } catch (e: Exception) {
        Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建图片文件失败: ${e.message}", e)
        throw e
    }
}

/**
 * 创建视频文件
 */
private fun createVideoFile(context: android.content.Context): File {
    try {
        val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
        val storageDir = File(context.getExternalFilesDir(Environment.DIRECTORY_MOVIES), "Camera")
        
        Log.d(LogTags.APPROVAL_SCREEN, "📁 创建视频文件目录: ${storageDir.absolutePath}")
        
        // 确保目录存在
        if (!storageDir.exists()) {
            val created = storageDir.mkdirs()
            Log.d(LogTags.APPROVAL_SCREEN, "📁 创建目录结果: $created")
        }
        
        val fileName = "VIDEO_${timeStamp}_"
        val fileExtension = ".mp4"
        
        Log.d(LogTags.APPROVAL_SCREEN, "📁 创建视频文件: $fileName$fileExtension")
        
        val file = File.createTempFile(fileName, fileExtension, storageDir)
        Log.i(LogTags.APPROVAL_SCREEN, "✅ 视频文件创建成功: ${file.absolutePath}")
        
        return file
    } catch (e: Exception) {
        Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建视频文件失败: ${e.message}", e)
        throw e
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ApprovalScreen(
    onNavigateBack: () -> Unit,
    formId: Int? = null,
    templateId: Int? = null,
    projectId: Int? = null,
    memberId: Int? = null,
    elevatorId: Int? = null,
    onNavigateToFileViewer: (String, String) -> Unit = { _, _ -> }
) {
    // 输出接收到的参数
    Log.i(LogTags.APPROVAL_SCREEN, "📱 ApprovalScreen 接收参数:")
    Log.i(LogTags.APPROVAL_SCREEN, "   🆔 formId: $formId")
    Log.i(LogTags.APPROVAL_SCREEN, "   📄 templateId: $templateId")
    Log.i(LogTags.APPROVAL_SCREEN, "   🏗️ projectId: $projectId")
    Log.i(LogTags.APPROVAL_SCREEN, "   👤 memberId: $memberId")
    Log.i(LogTags.APPROVAL_SCREEN, "   🛗 elevatorId: $elevatorId")
    
    val context = LocalContext.current
      
      // 初始化定位管理器 - 使用 DisposableEffect 确保正确清理
      val locationManager = remember { LocationManager(context) }
      
      // 监听位置信息
      val currentLocation by locationManager.currentLocation.collectAsState()
      val locationError by locationManager.errorMessage.collectAsState()
      
      // 确保 LocationManager 正确清理
      DisposableEffect(Unit) {
          onDispose {
              try {
                  locationManager.stopLocationUpdates()
                  Log.i(LogTags.APPROVAL_SCREEN, "✅ LocationManager 已清理")
              } catch (e: Exception) {
                  Log.e(LogTags.APPROVAL_SCREEN, "❌ LocationManager 清理失败: ${e.message}", e)
              }
          }
      }
      
      // 全局权限请求器 - 在应用启动时就请求权限
      val globalPermissionLauncher = rememberLauncherForActivityResult(
          contract = ActivityResultContracts.RequestMultiplePermissions()
      ) { permissions ->
          val allGranted = permissions.values.all { it }
          val grantedPermissions = permissions.filter { it.value }.keys
          val deniedPermissions = permissions.filter { !it.value }.keys
          
          Log.i(LogTags.APPROVAL_SCREEN, "🔐 全局权限请求结果:")
          Log.i(LogTags.APPROVAL_SCREEN, "   ✅ 已授权: ${grantedPermissions.joinToString()}")
          if (deniedPermissions.isNotEmpty()) {
              Log.w(LogTags.APPROVAL_SCREEN, "   ❌ 被拒绝: ${deniedPermissions.joinToString()}")
          }
          
          if (allGranted) {
              Log.i(LogTags.APPROVAL_SCREEN, "✅ 所有权限已获取，可以正常使用拍照和拍视频功能")
          } else {
              Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 部分权限被拒绝，可能影响拍照和拍视频功能")
          }
          
          // 更新权限状态缓存
          val camera = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
          val audio = ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
          val storage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
              ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
          } else {
              ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
          }
          
          Log.d(LogTags.APPROVAL_SCREEN, "🔐 权限状态更新 - 相机: $camera, 音频: $audio, 存储: $storage")
      }
      
      // 延迟权限请求和位置获取，避免在初始化时立即执行
      LaunchedEffect(Unit) {
          // 延迟执行，确保页面完全初始化
          delay(500)
          
          val permissionsToRequest = mutableListOf<String>()
          
          // 检查相机权限
          if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
              permissionsToRequest.add(android.Manifest.permission.CAMERA)
          }
          
          // 检查录音权限
          if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
              permissionsToRequest.add(android.Manifest.permission.RECORD_AUDIO)
          }
          
          // 检查存储权限（根据Android版本）
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
              // Android 13+ 使用新的媒体权限
              if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES) != PackageManager.PERMISSION_GRANTED) {
                  permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_IMAGES)
              }
              if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_VIDEO) != PackageManager.PERMISSION_GRANTED) {
                  permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_VIDEO)
              }
              if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_AUDIO) != PackageManager.PERMISSION_GRANTED) {
                  permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_AUDIO)
              }
          } else {
              // Android 12 及以下使用传统存储权限
              if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                  permissionsToRequest.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
              }
              if (ContextCompat.checkSelfPermission(context, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                  permissionsToRequest.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
              }
          }
          
          if (permissionsToRequest.isNotEmpty()) {
              Log.i(LogTags.APPROVAL_SCREEN, "🔐 预请求权限: ${permissionsToRequest.joinToString()}")
              globalPermissionLauncher.launch(permissionsToRequest.toTypedArray())
          } else {
              Log.i(LogTags.APPROVAL_SCREEN, "✅ 所有权限已获取")
          }
          
          // 初始化权限状态
          val camera = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
          val audio = ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
          val storage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
              ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
          } else {
              ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
          }
          
          Log.d(LogTags.APPROVAL_SCREEN, "🔐 初始权限状态 - 相机: $camera, 音频: $audio, 存储: $storage")
          
          // 延迟开始获取位置信息
          delay(1000)
          Log.i(LogTags.APPROVAL_SCREEN, "📍 开始获取当前位置信息...")
          try {
              locationManager.startLocationUpdates()
          } catch (e: Exception) {
              Log.e(LogTags.APPROVAL_SCREEN, "❌ 启动位置更新失败: ${e.message}", e)
          }
      }
      
      // 监听位置变化并输出位置信息
      LaunchedEffect(currentLocation) {
          if (currentLocation != null) {
              Log.i(LogTags.APPROVAL_SCREEN, "📍 获取到当前位置信息:")
              Log.i(LogTags.APPROVAL_SCREEN, locationManager.getDetailedLocationInfo())
              
              // 输出位置信息到控制台
              println("📍 ApprovalScreen - 当前位置信息:")
              println(locationManager.getDetailedLocationInfo())
          }
      }
      
      // 监听定位错误
      LaunchedEffect(locationError) {
          if (locationError != null) {
              Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 定位错误: $locationError")
              println("⚠️ ApprovalScreen - 定位错误: $locationError")
          }
      }
    
    // 设置全局异常处理器
    LaunchedEffect(Unit) {
        try {
            val defaultHandler = Thread.getDefaultUncaughtExceptionHandler()
            Thread.setDefaultUncaughtExceptionHandler { thread, exception ->
                Log.e(LogTags.APPROVAL_SCREEN, "❌ 未捕获的异常: ${exception.message}", exception)
                Log.e(LogTags.APPROVAL_SCREEN, "❌ 异常线程: ${thread.name}")
                Log.e(LogTags.APPROVAL_SCREEN, "❌ 异常堆栈:", exception)
                
                // 调用默认处理器
                defaultHandler?.uncaughtException(thread, exception)
            }
            Log.i(LogTags.APPROVAL_SCREEN, "✅ 全局异常处理器设置成功")
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 设置全局异常处理器失败: ${e.message}", e)
        }
    }
    var pageTitle by remember { mutableStateOf("加载中...") }
    var isLoading by remember { mutableStateOf(true) }
    
    // 文件上传相关状态
    var fileUploadCallback by remember { mutableStateOf<ValueCallback<Array<Uri>>?>(null) }
    var cameraImageUri by remember { mutableStateOf<Uri?>(null) }
    var cameraVideoUri by remember { mutableStateOf<Uri?>(null) }
    
    // 错误处理和用户反馈状态
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var showErrorDialog by remember { mutableStateOf(false) }
    var isProcessingFile by remember { mutableStateOf(false) }
    
    // 跟踪当前操作类型
    var currentOperation by remember { mutableStateOf<String?>(null) }
    
    // 页面状态管理 - 简化状态变量
    var isPageInitialized by remember { mutableStateOf(false) }
    var isProcessingFileUpload by remember { mutableStateOf(false) }
    var operationStartTime by remember { mutableStateOf(0L) }
    
    // 页面重载检测
    var pageLoadCount by remember { mutableStateOf(0) }
    
    // 权限状态缓存
    var cameraPermissionGranted by remember { mutableStateOf(false) }
    var audioPermissionGranted by remember { mutableStateOf(false) }
    var storagePermissionGranted by remember { mutableStateOf(false) }
    
    // 实时检查权限状态
    fun checkPermissionsStatus(): Triple<Boolean, Boolean, Boolean> {
        val camera = ContextCompat.checkSelfPermission(context, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED
        val audio = ContextCompat.checkSelfPermission(context, android.Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
        val storage = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
            ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_MEDIA_IMAGES) == PackageManager.PERMISSION_GRANTED
        } else {
            ContextCompat.checkSelfPermission(context, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
        }
        
        // 更新缓存状态
        cameraPermissionGranted = camera
        audioPermissionGranted = audio
        storagePermissionGranted = storage
        
        Log.d(LogTags.APPROVAL_SCREEN, "🔐 实时权限检查 - 相机: $camera, 音频: $audio, 存储: $storage")
        return Triple(camera, audio, storage)
    }
    
    // 检查系统内存状态
    fun checkMemoryStatus(): Boolean {
        try {
            val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val memoryInfo = ActivityManager.MemoryInfo()
            activityManager.getMemoryInfo(memoryInfo)
            
            val availableMemoryMB = memoryInfo.availMem / (1024 * 1024)
            val totalMemoryMB = memoryInfo.totalMem / (1024 * 1024)
            val memoryUsagePercent = ((totalMemoryMB - availableMemoryMB) * 100) / totalMemoryMB
            
            Log.i(LogTags.APPROVAL_SCREEN, "💾 内存状态检查:")
            Log.i(LogTags.APPROVAL_SCREEN, "   📊 总内存: ${totalMemoryMB}MB")
            Log.i(LogTags.APPROVAL_SCREEN, "   📊 可用内存: ${availableMemoryMB}MB")
            Log.i(LogTags.APPROVAL_SCREEN, "   📊 内存使用率: ${memoryUsagePercent}%")
            
            // 如果内存使用率超过85%，建议不要拍照
            if (memoryUsagePercent > 85) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 内存使用率过高: ${memoryUsagePercent}%")
                return false
            }
            
            // 如果可用内存少于200MB，不建议拍照
            if (availableMemoryMB < 200) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 可用内存不足: ${availableMemoryMB}MB")
                return false
            }
            
            Log.i(LogTags.APPROVAL_SCREEN, "✅ 内存状态良好，可以拍照")
            return true
            
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 内存检查失败: ${e.message}", e)
            return true // 如果检查失败，允许拍照
        }
    }
    
    // 显示错误信息的函数
    fun showError(message: String) {
        Log.e(LogTags.APPROVAL_SCREEN, "❌ 错误: $message")
        errorMessage = message
        showErrorDialog = true
        isProcessingFile = false
        isProcessingFileUpload = false
        operationStartTime = 0L
        
        // 移除Toast提示，只保留弹窗
        
        // 清理文件上传回调
        fileUploadCallback?.onReceiveValue(null)
        fileUploadCallback = null
    }
    
    // 显示成功信息的函数
    fun showSuccess(message: String) {
        Log.i(LogTags.APPROVAL_SCREEN, "✅ 成功: $message")
        // 移除Toast提示，只保留弹窗
        isProcessingFile = false
        isProcessingFileUpload = false
        operationStartTime = 0L
    }
    
    // 文件选择器启动器
    val fileChooserLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri: Uri? ->
        try {
            Log.d(LogTags.APPROVAL_SCREEN, "📁 文件选择器回调触发")
            Log.i(LogTags.APPROVAL_SCREEN, "📁 文件选择结果: $uri")
            Log.i(LogTags.APPROVAL_SCREEN, "📁 当前fileUploadCallback状态: ${fileUploadCallback != null}")
            Log.i(LogTags.APPROVAL_SCREEN, "📁 页面初始化状态: $isPageInitialized")
            
            // 如果用户取消了文件选择，重置状态
            if (uri == null) {
                Log.i(LogTags.APPROVAL_SCREEN, "📁 用户取消了文件选择")
                isProcessingFile = false
                isProcessingFileUpload = false
                currentOperation = null
                operationStartTime = 0L
                
                // 通知WebView取消操作
                try {
                    fileUploadCallback?.onReceiveValue(null)
                    Log.i(LogTags.APPROVAL_SCREEN, "✅ 文件选择取消回调调用成功")
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 文件选择取消回调调用失败: ${e.message}", e)
                }
                fileUploadCallback = null
                return@rememberLauncherForActivityResult
            }
            
            // 检查页面是否已初始化
            if (!isPageInitialized) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 页面未初始化，延迟处理文件选择")
                // 延迟处理，等待页面初始化完成
                @Suppress("OPT_IN_USAGE")
                GlobalScope.launch {
                    delay(100)
                    if (fileUploadCallback != null) {
                        uri.let {
                            fileUploadCallback?.onReceiveValue(arrayOf(it))
                            // 移除Toast提示，只保留弹窗
                        } ?: run {
                            fileUploadCallback?.onReceiveValue(null)
                        }
                        fileUploadCallback = null
                    }
                }
                return@rememberLauncherForActivityResult
            }
            
            isProcessingFile = true
            isProcessingFileUpload = true
            operationStartTime = System.currentTimeMillis()
            
            uri.let {
                Log.i(LogTags.APPROVAL_SCREEN, "📁 文件选择成功: $it")
                Log.i(LogTags.APPROVAL_SCREEN, "📁 文件路径: ${it.path}")
                Log.i(LogTags.APPROVAL_SCREEN, "📁 文件scheme: ${it.scheme}")
                Log.i(LogTags.APPROVAL_SCREEN, "📁 文件authority: ${it.authority}")
                
                // 检查文件是否存在
                try {
                    val file = File(it.path ?: "")
                    Log.i(LogTags.APPROVAL_SCREEN, "📁 文件存在检查: ${file.exists()}")
                    if (file.exists()) {
                        Log.i(LogTags.APPROVAL_SCREEN, "📁 文件大小: ${file.length()} bytes")
                    }
                } catch (e: Exception) {
                    Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 无法检查文件状态: ${e.message}")
                }
                
                // 调用WebView回调
                try {
                    Log.i(LogTags.APPROVAL_SCREEN, "📁 准备调用WebView回调...")
                    fileUploadCallback?.onReceiveValue(arrayOf(it))
                    Log.i(LogTags.APPROVAL_SCREEN, "✅ WebView回调调用成功")
                    showSuccess("文件选择成功")
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ WebView回调调用失败: ${e.message}", e)
                    showError("文件上传失败: ${e.message}")
                }
            }
            
            Log.i(LogTags.APPROVAL_SCREEN, "📁 清理fileUploadCallback")
            fileUploadCallback = null
            isProcessingFile = false
            Log.i(LogTags.APPROVAL_SCREEN, "📁 文件选择处理完成")
            
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 文件选择处理失败: ${e.message}", e)
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 异常堆栈:", e)
            showError("文件选择处理失败: ${e.message}")
            isProcessingFile = false
        }
    }
    
    // 相机启动器
    val cameraLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.TakePicture()
    ) { success: Boolean ->
        try {
            // 相机操作时间统计已简化
            
            Log.d(LogTags.APPROVAL_SCREEN, "📷 拍照结果: $success")
            Log.i(LogTags.APPROVAL_SCREEN, "📷 页面初始化状态: $isPageInitialized")
            
            // 相机操作完成
            
            // 如果用户取消了拍照，重置状态
            if (!success) {
                Log.i(LogTags.APPROVAL_SCREEN, "📷 用户取消了拍照")
                isProcessingFile = false
                isProcessingFileUpload = false
                currentOperation = null
                operationStartTime = 0L
                
                // 通知WebView取消操作
                try {
                    fileUploadCallback?.onReceiveValue(null)
                    Log.i(LogTags.APPROVAL_SCREEN, "✅ 拍照取消回调调用成功")
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 拍照取消回调调用失败: ${e.message}", e)
                }
                fileUploadCallback = null
                cameraImageUri = null
                return@rememberLauncherForActivityResult
            }
            
            // 检查页面是否已初始化
            if (!isPageInitialized) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 页面未初始化，延迟处理拍照结果")
                // 延迟处理，等待页面初始化完成
                @Suppress("OPT_IN_USAGE")
                GlobalScope.launch {
                    delay(100)
                    if (success && cameraImageUri != null && fileUploadCallback != null) {
                        fileUploadCallback?.onReceiveValue(arrayOf(cameraImageUri!!))
                        // 移除Toast提示，只保留弹窗
                        fileUploadCallback = null
                        cameraImageUri = null
                    }
                }
                return@rememberLauncherForActivityResult
            }
            
            isProcessingFile = true
            isProcessingFileUpload = true
            operationStartTime = System.currentTimeMillis()
            
            if (success && cameraImageUri != null) {
                Log.i(LogTags.APPROVAL_SCREEN, "✅ 拍照成功，文件URI: $cameraImageUri")
                
                // 验证文件是否存在
                try {
                    val contentResolver = context.contentResolver
                    val cursor = contentResolver.query(cameraImageUri!!, null, null, null, null)
                    val fileExists = cursor?.use { it.count > 0 } ?: false
                    cursor?.close()
                    
                    if (fileExists) {
                        Log.i(LogTags.APPROVAL_SCREEN, "✅ 拍照文件验证成功")
                        fileUploadCallback?.onReceiveValue(arrayOf(cameraImageUri!!))
                        showSuccess("拍照成功")
                    } else {
                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 拍照文件不存在或为空")
                        showError("拍照失败：文件未正确保存")
                    }
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 拍照文件验证失败: ${e.message}", e)
                    // 即使验证失败，也尝试上传文件
                    fileUploadCallback?.onReceiveValue(arrayOf(cameraImageUri!!))
                    showSuccess("拍照成功")
                }
            } else {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 拍照失败或取消")
                fileUploadCallback?.onReceiveValue(null)
            }
            fileUploadCallback = null
            cameraImageUri = null
            isProcessingFile = false
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 拍照处理失败: ${e.message}", e)
            showError("拍照处理失败: ${e.message}")
            cameraImageUri = null
        }
    }
    
    // 视频录制启动器
    val videoLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.CaptureVideo()
    ) { success: Boolean ->
        try {
            Log.d(LogTags.APPROVAL_SCREEN, "🎥 录制视频结果: $success")
            Log.i(LogTags.APPROVAL_SCREEN, "🎥 页面初始化状态: $isPageInitialized")
            
            // 如果用户取消了录制，重置状态
            if (!success) {
                Log.i(LogTags.APPROVAL_SCREEN, "🎥 用户取消了视频录制")
                isProcessingFile = false
                isProcessingFileUpload = false
                currentOperation = null
                operationStartTime = 0L
                
                // 通知WebView取消操作
                try {
                    fileUploadCallback?.onReceiveValue(null)
                    Log.i(LogTags.APPROVAL_SCREEN, "✅ 视频录制取消回调调用成功")
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 视频录制取消回调调用失败: ${e.message}", e)
                }
                fileUploadCallback = null
                cameraVideoUri = null
                return@rememberLauncherForActivityResult
            }
            
            // 检查页面是否已初始化
            if (!isPageInitialized) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 页面未初始化，延迟处理视频录制结果")
                // 延迟处理，等待页面初始化完成
                @Suppress("OPT_IN_USAGE")
                GlobalScope.launch {
                    delay(100)
                    if (success && cameraVideoUri != null && fileUploadCallback != null) {
                        fileUploadCallback?.onReceiveValue(arrayOf(cameraVideoUri!!))
                        // 移除Toast提示，只保留弹窗
                        fileUploadCallback = null
                        cameraVideoUri = null
                    }
                }
                return@rememberLauncherForActivityResult
            }
            
            isProcessingFile = true
            isProcessingFileUpload = true
            operationStartTime = System.currentTimeMillis()
            
            if (success && cameraVideoUri != null) {
                Log.i(LogTags.APPROVAL_SCREEN, "✅ 录制视频成功，文件URI: $cameraVideoUri")
                
                // 验证文件是否存在
                try {
                    val contentResolver = context.contentResolver
                    val cursor = contentResolver.query(cameraVideoUri!!, null, null, null, null)
                    val fileExists = cursor?.use { it.count > 0 } ?: false
                    cursor?.close()
                    
                    if (fileExists) {
                        Log.i(LogTags.APPROVAL_SCREEN, "✅ 视频文件验证成功")
                        fileUploadCallback?.onReceiveValue(arrayOf(cameraVideoUri!!))
                        showSuccess("视频录制成功")
                    } else {
                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 视频文件不存在或为空")
                        showError("视频录制失败：文件未正确保存")
                    }
                } catch (e: Exception) {
                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 视频文件验证失败: ${e.message}", e)
                    // 即使验证失败，也尝试上传文件
                    fileUploadCallback?.onReceiveValue(arrayOf(cameraVideoUri!!))
                    showSuccess("视频录制成功")
                }
            } else {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 录制视频失败或取消")
                fileUploadCallback?.onReceiveValue(null)
            }
            fileUploadCallback = null
            cameraVideoUri = null
            isProcessingFile = false
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 视频录制处理失败: ${e.message}", e)
            showError("视频录制处理失败: ${e.message}")
            cameraVideoUri = null
        }
    }
    
    // 权限请求启动器
    val permissionLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.RequestMultiplePermissions()
    ) { permissions ->
        try {
            val cameraPermission = permissions[android.Manifest.permission.CAMERA] ?: false
            val audioPermission = permissions[android.Manifest.permission.RECORD_AUDIO] ?: false
            val storagePermission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                permissions[android.Manifest.permission.READ_MEDIA_IMAGES] ?: false
            } else {
                permissions[android.Manifest.permission.READ_EXTERNAL_STORAGE] ?: false
            }
            
            Log.d(LogTags.APPROVAL_SCREEN, "🔐 权限请求结果 - 相机: $cameraPermission, 音频: $audioPermission, 存储: $storagePermission")
            
            // 检查相机权限（拍照和拍视频都需要）
            if (!cameraPermission) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 相机权限被拒绝")
                showError("相机权限被拒绝，无法使用拍照和拍视频功能")
                return@rememberLauncherForActivityResult
            }
            
            // 检查存储权限（拍照和拍视频都需要）
            if (!storagePermission) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 存储权限被拒绝")
                showError("存储权限被拒绝，无法保存照片和视频")
                return@rememberLauncherForActivityResult
            }
            
            // 根据操作类型决定后续操作
            when (currentOperation) {
                "photo" -> {
                    // 拍照操作
                    try {
                        val photoFile = createImageFile(context)
                        cameraImageUri = FileProvider.getUriForFile(
                            context,
                            "${context.packageName}.fileprovider",
                            photoFile
                        )
                        Log.i(LogTags.APPROVAL_SCREEN, "📷 权限获取成功，启动相机拍照: $cameraImageUri")
                        cameraLauncher.launch(cameraImageUri)
                    } catch (e: Exception) {
                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建拍照文件失败: ${e.message}", e)
                        showError("创建拍照文件失败: ${e.message}")
                    }
                }
                "video" -> {
                    // 拍视频操作
                    if (audioPermission) {
                        try {
                            val videoFile = createVideoFile(context)
                            cameraVideoUri = FileProvider.getUriForFile(
                                context,
                                "${context.packageName}.fileprovider",
                                videoFile
                            )
                            Log.i(LogTags.APPROVAL_SCREEN, "🎥 权限获取成功，启动视频录制: $cameraVideoUri")
                            videoLauncher.launch(cameraVideoUri)
                        } catch (e: Exception) {
                            Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建视频文件失败: ${e.message}", e)
                            showError("创建视频文件失败: ${e.message}")
                        }
                    } else {
                        Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 音频权限被拒绝，无法录制视频")
                        showError("音频权限被拒绝，无法录制视频")
                    }
                }
                else -> {
                    Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 未知操作类型: $currentOperation")
                }
            }
            
            // 清理操作类型
            currentOperation = null
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 权限处理失败: ${e.message}", e)
            showError("权限处理失败: ${e.message}")
        }
    }
    
    // 获取本地存储的token并拼接URL - 使用更安全的方式
    val initialUrl = remember(formId, templateId, projectId, memberId, elevatorId) {
        try {
            val tokenManager = com.sinogrand.elevator.utils.TokenManager(context)
            val environmentManager = EnvironmentManager(context)
            val token = tokenManager.getToken()
            
            if (token.isEmpty()) {
                Log.e(LogTags.APPROVAL_SCREEN, "❌ Token为空，无法加载审批页面")
                return@remember "about:blank"
            }
            
            // 获取当前环境的审批流程URL
            val baseUrl = environmentManager.getCurrentApprovalFlowUrl()
            val urlBuilder = StringBuilder("$baseUrl/approval-flow?token=$token")
            
            // 处理 form_id
            if (formId != null) {
                urlBuilder.append("&form_id=$formId")
            }
            
            // 处理 template_id
            if (templateId != null) {
                urlBuilder.append("&template_id=$templateId")
            }
            
            // 处理 extra 中的参数
            if (projectId != null) {
                urlBuilder.append("&project_id=$projectId")
            }
            
            if (memberId != null) {
                urlBuilder.append("&member_id=$memberId")
            }
            
            if (elevatorId != null) {
                urlBuilder.append("&elevator_id=$elevatorId")
            }
            
            val url = urlBuilder.toString()
            
            Log.i(LogTags.APPROVAL_SCREEN, "🔗 拼接好的访问URL: $url")
            Log.i(LogTags.APPROVAL_SCREEN, "📋 URL参数详情:")
            Log.i(LogTags.APPROVAL_SCREEN, "   🔑 token: $token")
            Log.i(LogTags.APPROVAL_SCREEN, "   🆔 formId: $formId")
            Log.i(LogTags.APPROVAL_SCREEN, "   📄 templateId: $templateId")
            Log.i(LogTags.APPROVAL_SCREEN, "   🏗️ projectId: $projectId")
            Log.i(LogTags.APPROVAL_SCREEN, "   👤 memberId: $memberId")
            Log.i(LogTags.APPROVAL_SCREEN, "   🛗 elevatorId: $elevatorId")
            
            url
        } catch (e: Exception) {
            Log.e(LogTags.APPROVAL_SCREEN, "❌ 构建URL失败: ${e.message}", e)
            "about:blank"
        }
    }
    
    var currentUrl by remember { mutableStateOf(initialUrl) }
    
    // 检测页面重新加载情况
    LaunchedEffect(Unit) {
        Log.i(LogTags.APPROVAL_SCREEN, "🔄 ApprovalScreen LaunchedEffect 触发")
        Log.i(LogTags.APPROVAL_SCREEN, "🔄 页面初始化状态: $isPageInitialized")
        Log.i(LogTags.APPROVAL_SCREEN, "🔄 文件上传处理状态: $isProcessingFileUpload")
        
        // 页面初始化时重置所有状态，确保干净的状态
        if (!isPageInitialized) {
            Log.i(LogTags.APPROVAL_SCREEN, "🔄 页面初始化，重置所有状态")
            isProcessingFileUpload = false
            isProcessingFile = false
            currentOperation = null
            operationStartTime = 0L
        }
    }
    
    // 操作超时检测
    LaunchedEffect(isProcessingFile, operationStartTime) {
        if (isProcessingFile && operationStartTime > 0) {
            val timeoutDuration = 30000L // 30秒超时
            val elapsedTime = System.currentTimeMillis() - operationStartTime
            
            if (elapsedTime > timeoutDuration) {
                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 操作超时: ${elapsedTime}ms，重置状态")
                isProcessingFile = false
                isProcessingFileUpload = false
                currentOperation = null
                operationStartTime = 0L
                showError("操作超时，请重试")
            }
        }
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = pageTitle,
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        maxLines = 1,
                        overflow = TextOverflow.Ellipsis
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    titleContentColor = MaterialTheme.colorScheme.onPrimaryContainer,
                    navigationIconContentColor = MaterialTheme.colorScheme.onPrimaryContainer
                )
            )
        }
    ) { paddingValues ->
        // WebView容器 - 延伸到系统导航栏区域，底部挨着物理按键
        Box(
            modifier = Modifier
                .fillMaxSize()
                .padding(top = paddingValues.calculateTopPadding())
                // 移除底部padding，让WebView延伸到系统导航栏区域
        ) {
            AndroidView(
                factory = { context ->
                    WebView(context).apply {
                        // 确保WebView有正确的布局参数
                        layoutParams = android.view.ViewGroup.LayoutParams(
                            android.view.ViewGroup.LayoutParams.MATCH_PARENT,
                            android.view.ViewGroup.LayoutParams.MATCH_PARENT
                        )
                        
                        // 设置WebView延伸到系统导航栏区域
                        fitsSystemWindows = false
                        
                        // 设置WebView的clipToPadding为false，确保内容可以延伸到padding区域
                        clipToPadding = false
                        
                        // 设置WebView的scrollBarStyle为OVERLAY_CONTENT，避免滚动条占用空间
                        scrollBarStyle = android.view.View.SCROLLBARS_OUTSIDE_OVERLAY
                        settings.apply {
                            javaScriptEnabled = true
                            domStorageEnabled = true
                            loadWithOverviewMode = true
                            useWideViewPort = true
                            setSupportZoom(true)
                            builtInZoomControls = true
                            displayZoomControls = false
                            // 添加这些设置来确保内容正确显示
                            mixedContentMode = android.webkit.WebSettings.MIXED_CONTENT_ALWAYS_ALLOW
                            allowFileAccess = true
                            allowContentAccess = true
                            @Suppress("DEPRECATION")
                            allowFileAccessFromFileURLs = true
                            @Suppress("DEPRECATION")
                            allowUniversalAccessFromFileURLs = true
                            // 设置用户代理
                            userAgentString = userAgentString + " ElevatorApp/1.0"
                            // 添加缓存设置
                            cacheMode = android.webkit.WebSettings.LOAD_DEFAULT
                            // 设置数据库启用
                            databaseEnabled = true
                        }

                        webViewClient = object : WebViewClient() {
                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onPageFinished(view: WebView?, url: String?) {
                                super.onPageFinished(view, url)
                                pageLoadCount++
                                Log.d(LogTags.APPROVAL_SCREEN, "✅ 页面加载完成: $url (第${pageLoadCount}次加载)")
                                isLoading = false
                                currentUrl = url ?: initialUrl
                                
                                // 检测页面重载 - 统一重置策略
                                if (pageLoadCount > 1) {
                                    Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 检测到页面重载，重置所有状态")
                                    isProcessingFileUpload = false
                                    isProcessingFile = false
                                    currentOperation = null
                                    operationStartTime = 0L
                                    Log.i(LogTags.APPROVAL_SCREEN, "🔄 页面重载后状态已重置")
                                }
                                
                                // 添加调试信息
                                view?.let { webView ->
                                    Log.d(LogTags.APPROVAL_SCREEN, "📱 WebView尺寸: ${webView.width}x${webView.height}")
                                    Log.d(LogTags.APPROVAL_SCREEN, "📱 WebView可见性: ${webView.visibility}")
                                    Log.d(LogTags.APPROVAL_SCREEN, "📱 WebView透明度: ${webView.alpha}")
                                    
                                    // 检查页面内容
                                    try {
                                        webView.evaluateJavascript("document.body.innerHTML.length") { result ->
                                            Log.d(LogTags.APPROVAL_SCREEN, "📄 页面内容长度: $result")
                                        }
                                        
                                        webView.evaluateJavascript("document.body.scrollHeight") { result ->
                                            Log.d(LogTags.APPROVAL_SCREEN, "📏 页面高度: $result")
                                        }
                                        
                                        // 添加JavaScript错误监听
                                        webView.evaluateJavascript("""
                                            window.addEventListener('error', function(e) {
                                                console.error('JavaScript Error:', e.message, 'at', e.filename + ':' + e.lineno);
                                            });
                                            window.addEventListener('unhandledrejection', function(e) {
                                                console.error('Unhandled Promise Rejection:', e.reason);
                                            });
                                        """.trimIndent()) { result ->
                                            Log.d(LogTags.APPROVAL_SCREEN, "📄 JavaScript错误监听器设置结果: $result")
                                        }
                                    } catch (e: Exception) {
                                        Log.e(LogTags.APPROVAL_SCREEN, "❌ JavaScript执行失败: ${e.message}", e)
                                    }
                                }
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onPageStarted(view: WebView?, url: String?, favicon: android.graphics.Bitmap?) {
                                super.onPageStarted(view, url, favicon)
                                Log.d(LogTags.APPROVAL_SCREEN, "🔄 开始加载页面: $url")
                                isLoading = true
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onReceivedError(view: WebView?, errorCode: Int, description: String?, failingUrl: String?) {
                                super.onReceivedError(view, errorCode, description, failingUrl)
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ WebView加载错误 - 错误码: $errorCode, 描述: $description, URL: $failingUrl")
                                isLoading = false
                                pageTitle = "加载失败"
                                
                                // 如果是网络错误，尝试重新加载
                                if (errorCode == -2 || errorCode == -6) { // 网络相关错误
                                    Log.i(LogTags.APPROVAL_SCREEN, "🔄 检测到网络错误，尝试重新加载...")
                                    view?.postDelayed({
                                        try {
                                            view.loadUrl(initialUrl)
                                        } catch (e: Exception) {
                                            Log.e(LogTags.APPROVAL_SCREEN, "❌ 重新加载失败: ${e.message}", e)
                                        }
                                    }, 2000)
                                }
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun onReceivedHttpError(view: WebView?, request: android.webkit.WebResourceRequest?, errorResponse: android.webkit.WebResourceResponse?) {
                                super.onReceivedHttpError(view, request, errorResponse)
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ HTTP错误 - 状态码: ${errorResponse?.statusCode}, URL: ${request?.url}")
                            }

                            @Suppress("DEPRECATION")
                            @Deprecated("Deprecated in Java")
                            override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {
                                Log.d(LogTags.APPROVAL_SCREEN, "🔗 拦截URL加载: $url")
                                url?.let {
                                    view?.loadUrl(it)
                                }
                                return true
                            }
                        }

                        webChromeClient = object : WebChromeClient() {
                            override fun onReceivedTitle(view: WebView?, title: String?) {
                                super.onReceivedTitle(view, title)
                                Log.d(LogTags.APPROVAL_SCREEN, "📄 接收到页面标题: $title")
                                // 如果标题是 "base-project"，则置空
                                val processedTitle = if (title == "base-project") {
                                    ""
                                } else {
                                    title ?: "审批页面"
                                }
                                pageTitle = processedTitle
                                Log.d(LogTags.APPROVAL_SCREEN, "📄 处理后的页面标题: '$processedTitle'")
                            }

                            override fun onProgressChanged(view: WebView?, newProgress: Int) {
                                super.onProgressChanged(view, newProgress)
                                Log.d(LogTags.APPROVAL_SCREEN, "📊 页面加载进度: $newProgress%")
                                // 可以在这里添加进度条显示
                            }

                            override fun onConsoleMessage(consoleMessage: android.webkit.ConsoleMessage?): Boolean {
                                consoleMessage?.let { message ->
                                    val level = when (message.messageLevel()) {
                                        android.webkit.ConsoleMessage.MessageLevel.ERROR -> "❌ ERROR"
                                        android.webkit.ConsoleMessage.MessageLevel.WARNING -> "⚠️ WARNING"
                                        android.webkit.ConsoleMessage.MessageLevel.LOG -> "📝 LOG"
                                        android.webkit.ConsoleMessage.MessageLevel.TIP -> "💡 TIP"
                                        android.webkit.ConsoleMessage.MessageLevel.DEBUG -> "🐛 DEBUG"
                                        else -> "📄 INFO"
                                    }
                                    Log.d(LogTags.APPROVAL_SCREEN, "🖥️ [$level] ${message.message()} (${message.sourceId()}:${message.lineNumber()})")
                                    
                                    // 过滤掉常见的、不影响功能的错误
                                    val messageText = message.message()
                                    val shouldIgnoreError = messageText.contains("Ignored attempt to cancel a touchend event") ||
                                                          messageText.contains("cancelable=false") ||
                                                          messageText.contains("scrolling is in progress") ||
                                                          messageText.contains("webpack-internal")
                                    
                                    // 如果是JavaScript错误且不是需要忽略的错误，显示给用户
                                    if (message.messageLevel() == android.webkit.ConsoleMessage.MessageLevel.ERROR && !shouldIgnoreError) {
                                        Log.e(LogTags.APPROVAL_SCREEN, "❌ JavaScript错误: ${message.message()}")
                                        showError("网页错误: ${message.message()}")
                                    } else if (shouldIgnoreError) {
                                        Log.d(LogTags.APPROVAL_SCREEN, "🔇 已忽略常见错误: ${message.message()}")
                                    }
                                }
                                return super.onConsoleMessage(consoleMessage)
                            }
                            
                            // 处理文件上传
                            override fun onShowFileChooser(
                                webView: WebView?,
                                filePathCallback: ValueCallback<Array<Uri>>?,
                                fileChooserParams: FileChooserParams?
                            ): Boolean {
                                Log.d(LogTags.APPROVAL_SCREEN, "📁 WebView 请求文件选择")
                                Log.i(LogTags.APPROVAL_SCREEN, "📁 WebView实例: ${webView != null}")
                                Log.i(LogTags.APPROVAL_SCREEN, "📁 filePathCallback: ${filePathCallback != null}")
                                Log.i(LogTags.APPROVAL_SCREEN, "📁 fileChooserParams: ${fileChooserParams != null}")
                                
                                if (fileChooserParams != null) {
                                    Log.i(LogTags.APPROVAL_SCREEN, "📁 文件选择参数:")
                                    Log.i(LogTags.APPROVAL_SCREEN, "   📄 标题: ${fileChooserParams.title}")
                                    Log.i(LogTags.APPROVAL_SCREEN, "   📄 文件名: ${fileChooserParams.filenameHint}")
                                    Log.i(LogTags.APPROVAL_SCREEN, "   📄 MIME类型: ${fileChooserParams.acceptTypes?.joinToString()}")
                                }
                                
                                try {
                                    fileUploadCallback = filePathCallback
                                    Log.i(LogTags.APPROVAL_SCREEN, "📁 fileUploadCallback设置成功")
                                } catch (e: Exception) {
                                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 设置fileUploadCallback失败: ${e.message}", e)
                                    return false
                                }
                                
                                // 创建选择对话框
                                val options = arrayOf("拍照", "拍视频", "从相册选择", "选择文件", "取消")
                                val builder = android.app.AlertDialog.Builder(context)
                                builder.setTitle("选择文件")
                                builder.setItems(options) { _, which ->
                                    when (which) {
                                        0 -> {
                                            // 拍照
                                            Log.d(LogTags.APPROVAL_SCREEN, "📷 用户选择拍照")
                                            currentOperation = "photo"
                                            
                                            // 检查内存状态
                                            if (!checkMemoryStatus()) {
                                                Log.w(LogTags.APPROVAL_SCREEN, "⚠️ 内存不足，建议稍后再试")
                                                showError("系统内存不足，建议稍后再试或选择其他文件")
                                                return@setItems
                                            }
                                            
                                            // 实时检查权限状态
                                            val (cameraPermission, _, storagePermission) = checkPermissionsStatus()
                                            
                                            Log.d(LogTags.APPROVAL_SCREEN, "🔐 拍照权限检查 - 相机: $cameraPermission, 存储: $storagePermission")
                                            
                                            if (cameraPermission && storagePermission) {
                                                // 权限已获取，直接拍照
                                                try {
                                                    Log.i(LogTags.APPROVAL_SCREEN, "📷 开始创建拍照文件...")
                                                    val photoFile = createImageFile(context)
                                                    cameraImageUri = FileProvider.getUriForFile(
                                                        context,
                                                        "${context.packageName}.fileprovider",
                                                        photoFile
                                                    )
                                                    Log.i(LogTags.APPROVAL_SCREEN, "📷 启动相机拍照: $cameraImageUri")
                                                    Log.i(LogTags.APPROVAL_SCREEN, "📷 拍照文件路径: ${photoFile.absolutePath}")
                                                    Log.i(LogTags.APPROVAL_SCREEN, "📷 拍照文件大小: ${photoFile.length()} bytes")
                                                    
                                                    // 记录拍照开始时间
                                                    // 开始拍照操作
                                                    
                                                    // 添加延迟，确保系统稳定
                                                    @Suppress("OPT_IN_USAGE")
                                                    GlobalScope.launch {
                                                        delay(100)
                                                        cameraLauncher.launch(cameraImageUri)
                                                    }
                                                } catch (e: Exception) {
                                                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建拍照文件失败: ${e.message}", e)
                                                    showError("创建拍照文件失败: ${e.message}")
                                                }
                                            } else {
                                                // 请求权限
                                                Log.d(LogTags.APPROVAL_SCREEN, "🔐 请求相机和存储权限")
                                                val permissionsToRequest = mutableListOf<String>()
                                                if (!cameraPermission) {
                                                    permissionsToRequest.add(android.Manifest.permission.CAMERA)
                                                }
                                                if (!storagePermission) {
                                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                        permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_IMAGES)
                                                    } else {
                                                        permissionsToRequest.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                                                    }
                                                }
                                                permissionLauncher.launch(permissionsToRequest.toTypedArray())
                                            }
                                        }
                                        1 -> {
                                            // 拍视频
                                            Log.d(LogTags.APPROVAL_SCREEN, "🎥 用户选择拍视频")
                                            currentOperation = "video"
                                            
                                            // 实时检查权限状态
                                            val (cameraPermission, audioPermission, storagePermission) = checkPermissionsStatus()
                                            
                                            Log.d(LogTags.APPROVAL_SCREEN, "🔐 拍视频权限检查 - 相机: $cameraPermission, 音频: $audioPermission, 存储: $storagePermission")
                                            
                                            if (cameraPermission && audioPermission && storagePermission) {
                                                // 权限已获取，直接录制视频
                                                try {
                                                    val videoFile = createVideoFile(context)
                                                    cameraVideoUri = FileProvider.getUriForFile(
                                                        context,
                                                        "${context.packageName}.fileprovider",
                                                        videoFile
                                                    )
                                                    Log.i(LogTags.APPROVAL_SCREEN, "🎥 启动视频录制: $cameraVideoUri")
                                                    Log.i(LogTags.APPROVAL_SCREEN, "🎥 视频文件路径: ${videoFile.absolutePath}")
                                                    Log.i(LogTags.APPROVAL_SCREEN, "🎥 视频文件大小: ${videoFile.length()} bytes")
                                                    videoLauncher.launch(cameraVideoUri)
                                                } catch (e: Exception) {
                                                    Log.e(LogTags.APPROVAL_SCREEN, "❌ 创建视频文件失败: ${e.message}", e)
                                                    showError("创建视频文件失败: ${e.message}")
                                                }
                                            } else {
                                                // 请求权限
                                                Log.d(LogTags.APPROVAL_SCREEN, "🔐 请求相机、音频和存储权限")
                                                val permissionsToRequest = mutableListOf<String>()
                                                if (!cameraPermission) {
                                                    permissionsToRequest.add(android.Manifest.permission.CAMERA)
                                                }
                                                if (!audioPermission) {
                                                    permissionsToRequest.add(android.Manifest.permission.RECORD_AUDIO)
                                                }
                                                if (!storagePermission) {
                                                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                                                        permissionsToRequest.add(android.Manifest.permission.READ_MEDIA_VIDEO)
                                                    } else {
                                                        permissionsToRequest.add(android.Manifest.permission.READ_EXTERNAL_STORAGE)
                                                    }
                                                }
                                                permissionLauncher.launch(permissionsToRequest.toTypedArray())
                                            }
                                        }
                                        2 -> {
                                            // 从相册选择
                                            Log.d(LogTags.APPROVAL_SCREEN, "🖼️ 用户选择从相册选择")
                                            fileChooserLauncher.launch("image/*")
                                        }
                                        3 -> {
                                            // 选择文件
                                            Log.d(LogTags.APPROVAL_SCREEN, "📄 用户选择文件")
                                            Log.i(LogTags.APPROVAL_SCREEN, "📄 准备启动文件选择器...")
                                            try {
                                                fileChooserLauncher.launch("*/*")
                                                Log.i(LogTags.APPROVAL_SCREEN, "📄 文件选择器启动成功")
                                            } catch (e: Exception) {
                                                Log.e(LogTags.APPROVAL_SCREEN, "❌ 启动文件选择器失败: ${e.message}", e)
                                                showError("启动文件选择器失败: ${e.message}")
                                            }
                                        }
                                        4 -> {
                                            // 取消
                                            Log.d(LogTags.APPROVAL_SCREEN, "❌ 用户取消文件选择")
                                            isProcessingFile = false
                                            isProcessingFileUpload = false
                                            currentOperation = null
                                            operationStartTime = 0L
                                            
                                            // 通知WebView取消操作
                                            try {
                                                fileUploadCallback?.onReceiveValue(null)
                                                Log.i(LogTags.APPROVAL_SCREEN, "✅ 取消选项回调调用成功")
                                            } catch (e: Exception) {
                                                Log.e(LogTags.APPROVAL_SCREEN, "❌ 取消选项回调调用失败: ${e.message}", e)
                                            }
                                            fileUploadCallback = null
                                        }
                                    }
                                }
                                builder.setOnCancelListener {
                                    Log.d(LogTags.APPROVAL_SCREEN, "❌ 用户取消文件选择对话框")
                                    isProcessingFile = false
                                    isProcessingFileUpload = false
                                    currentOperation = null
                                    operationStartTime = 0L
                                    
                                    // 通知WebView取消操作
                                    try {
                                        fileUploadCallback?.onReceiveValue(null)
                                        Log.i(LogTags.APPROVAL_SCREEN, "✅ 对话框取消回调调用成功")
                                    } catch (e: Exception) {
                                        Log.e(LogTags.APPROVAL_SCREEN, "❌ 对话框取消回调调用失败: ${e.message}", e)
                                    }
                                    fileUploadCallback = null
                                }
                                builder.show()
                                
                                return true
                            }
                        }

                        // 添加JavaScript接口
                        addJavascriptInterface(WebAppInterface(context, onNavigateBack, locationManager, this, onNavigateToFileViewer), "Android")
                        
                        // 延迟加载URL，确保WebView完全初始化
                        post {
                            try {
                                // 检查URL是否有效
                                if (initialUrl.isNotEmpty() && initialUrl != "about:blank") {
                                    loadUrl(initialUrl)
                                    Log.d(LogTags.APPROVAL_SCREEN, "🚀 WebView初始化完成，开始加载URL: $initialUrl")
                                } else {
                                    Log.e(LogTags.APPROVAL_SCREEN, "❌ URL无效，无法加载页面")
                                    showError("页面URL无效，请检查登录状态")
                                }
                                
                                // 设置页面初始化状态
                                isPageInitialized = true
                                Log.i(LogTags.APPROVAL_SCREEN, "✅ 页面初始化状态已设置")
                            } catch (e: Exception) {
                                Log.e(LogTags.APPROVAL_SCREEN, "❌ WebView加载URL失败: ${e.message}", e)
                                showError("页面加载失败: ${e.message}")
                            }
                        }
                    }
                },
                modifier = Modifier.fillMaxSize(),
                update = { webView ->
                    // 确保WebView在更新时保持状态
                    webView.requestLayout()
                }
            )

            // 加载指示器 - 只覆盖WebView区域，不覆盖导航栏
            if (isLoading) {
                Box(
                    modifier = Modifier
                        .matchParentSize()
                        .zIndex(1f),
                    contentAlignment = Alignment.Center
                ) {
                    Card(
                        colors = CardDefaults.cardColors(
                            containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f)
                        ),
                        elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                    ) {
                        Row(
                            modifier = Modifier.padding(16.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            CircularProgressIndicator(
                                modifier = Modifier.size(24.dp),
                                color = MaterialTheme.colorScheme.primary
                            )
                            Spacer(modifier = Modifier.width(12.dp))
                            Text(
                                text = "页面加载中...",
                                fontSize = 14.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                        }
                    }
                }
            }
        }
        
        // 错误对话框
        if (showErrorDialog && errorMessage != null) {
            AlertDialog(
                onDismissRequest = { 
                    showErrorDialog = false
                    errorMessage = null
                },
                title = {
                    Row(
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            imageVector = Icons.Default.Error,
                            contentDescription = "错误",
                            tint = MaterialTheme.colorScheme.error
                        )
                        Spacer(modifier = Modifier.width(8.dp))
                        Text("操作失败")
                    }
                },
                text = {
                    Text(errorMessage!!)
                },
                confirmButton = {
                    TextButton(
                        onClick = { 
                            showErrorDialog = false
                            errorMessage = null
                        }
                    ) {
                        Text("确定")
                    }
                }
            )
        }
        
        // 文件处理状态指示器
        if (isProcessingFile || isProcessingFileUpload) {
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .zIndex(2f),
                contentAlignment = Alignment.Center
            ) {
                Card(
                    colors = CardDefaults.cardColors(
                        containerColor = MaterialTheme.colorScheme.surface.copy(alpha = 0.9f)
                    ),
                    elevation = CardDefaults.cardElevation(defaultElevation = 8.dp)
                ) {
                    Row(
                        modifier = Modifier.padding(16.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = MaterialTheme.colorScheme.primary
                        )
                        Spacer(modifier = Modifier.width(12.dp))
                        Text(
                            text = if (isProcessingFileUpload) "正在处理文件上传..." else "正在处理文件...",
                            fontSize = 14.sp,
                            color = MaterialTheme.colorScheme.onSurface
                        )
                    }
                }
            }
        }
    }
}